package com.jthinker.web.controller.common;

import com.jthinker.bean.vo.Constant;
import com.jthinker.utils.RSAUtils;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;

public class InitListener implements ServletContextListener
{
    private static final Logger LOGGER = LoggerFactory.getLogger(InitListener.class);

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
        LOGGER.info("ServletContext init...");
        ServletContext servletContext = servletContextEvent.getServletContext();
        KeyPair keyPair = RSAUtils.getKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        servletContext.setAttribute(Constant.MODULUS, new String(Hex.encodeHex(publicKey.getModulus().toByteArray())));
        servletContext.setAttribute(Constant.EXPONENT, new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray())));

        LOGGER.info("ServletContext init finish...");

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent)
    {
        LOGGER.info("ServletContext destroyed...");
    }
}
